from django.conf import settings
from ebooks.models import Book


class Cart:
    def __init__(self, request):
        self.session = request.session
        cart = self.session.get(settings.CART_SESSION_ID)
        if not cart:
            cart = self.session[settings.CART_SESSION_ID] = {}
        self.cart = cart

    def add(self, book):
        book_id = str(book.id)
        if book_id not in self.cart:
            self.cart[book_id] = {
                'price': float(book.price),
            }
            self.save()

    def remove(self, book):
        book_id = str(book.id)
        if book_id in self.cart:
            del self.cart[book_id]
            self.save()

    def save(self):
        self.session.modified = True

    def __iter__(self):
        book_ids = self.cart.keys()
        books = Book.objects.filter(id__in=book_ids)
        for book in books:
            cart_item = self.cart[str(book.id)]
            cart_item['book'] = book
            cart_item['price'] = round(float(cart_item['price']), 2)
            cart_item['total_price'] = round(float(cart_item['price']), 2)
            yield cart_item

    def __len__(self):
        return len(self.cart)

    def get_total_price(self):
        return sum(item['price'] for item in self.cart.values())

    def clear(self):
        del self.session[settings.CART_SESSION_ID]
        self.save()